package com.jinlongchen.api;

import com.jinlongchen.util.DBUtil;
import com.jinlongchen.model.Album;
import com.jinlongchen.model.Story;
import com.jinlongchen.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/api/album-editor.json")
public class AlbumEidtorApi extends AbsApiServlet{
    @Override
    protected Object doGetInner(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ServletException, IOException, APIException {
        User currentUser =(User) req.getSession().getAttribute("currentUser");
        if (currentUser == null){
            throw new APIException("要求用户必须登录");
        }

        int aid = Integer.parseInt(req.getParameter("aid"));
        int uid;
        Album album = new Album();
        album.storyList = new ArrayList<>();
        try (Connection c = DBUtil.getConnection()) {
            {
                String sql = "SELECT aid,name,uid,cover FROM album WHERE aid = ?";
                try (PreparedStatement s = c.prepareStatement(sql)) {
                    s.setInt(1, aid);
                    try (ResultSet rs = s.executeQuery()) {
                        if (!rs.next()) {
                            throw new APIException("aid 对应的专辑不存在");
                        }
                        album.name = rs.getString("name");
                        album.cover = rs.getString("cover");
                        uid = rs.getInt("uid");
                    }
                }
            }

            if (uid != currentUser.uid) {
                throw new APIException("只有作者才有权限修改专辑");
            }

            //取故事列表
            {
                String sql = "SELECT sid,name FROM story WHERE aid = ? ORDER BY sid";
                try (PreparedStatement s = c.prepareStatement(sql)) {
                    s.setInt(1, aid);
                    try (ResultSet rs = s.executeQuery()) {
                        while (rs.next()) {
                            Story story = new Story();
                            story.sid = rs.getInt("sid");
                            story.name = rs.getString("name");

                            album.storyList.add(story);
                        }
                    }
                }
            }
        }
        return album;
    }
}
